﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.Services.Client;
using TelerikStore.EbayService;
using Telerik.Web.UI;
using TelerikStore.MasterPages;

namespace TelerikStore.Views
{
    public partial class ProductList_Grid : System.Web.UI.UserControl
    {
        public String SearchText { get; set; }
        public String ListedCategoryId { get; set; }
        public String FilterQueryString { get; set; }

        protected void Page_PreRender(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (!String.IsNullOrEmpty(ListedCategoryId) && !String.IsNullOrEmpty(SearchText))
                {
                    ProductGrid.ClientSettings.DataBinding.DataService.TableName = String.Format("Items?search={0}", SearchText);
                    ProductGrid.ClientSettings.DataBinding.DataService.FilterQueryOption = String.Format("{2}{1}PrimaryCategoryId%20eq%20'{0}'", ListedCategoryId, EbayQueryStringsHelper.And, FilterQueryString);
                }
                else if (!String.IsNullOrEmpty(ListedCategoryId))
                {
                    ProductGrid.ClientSettings.DataBinding.DataService.TableName = "Items";
                    ProductGrid.ClientSettings.DataBinding.DataService.FilterQueryOption = String.Format("{2}{1}PrimaryCategoryId%20eq%20'{0}'", ListedCategoryId, EbayQueryStringsHelper.And, FilterQueryString);
                }
                else
                {
                    ProductGrid.ClientSettings.DataBinding.DataService.TableName = String.Format("Items?search={0}", SearchText);
                    ProductGrid.ClientSettings.DataBinding.DataService.FilterQueryOption = FilterQueryString;
                }
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            RadAjaxManager ajaxManager = RadAjaxManager.GetCurrent(Page);
            ajaxManager.AjaxRequest += new RadAjaxControl.AjaxRequestDelegate(RadAjaxManager_AjaxRequest);
         }

        protected void RadAjaxManager_AjaxRequest(object sender, AjaxRequestEventArgs e)
        {
            if (e.Argument.StartsWith("AddToCart"))
            {
                var itemId = e.Argument.Split('|')[1];
                (Page.Master.Master as Home).AddItemToCart(itemId);
                //(Page as CategoryView1).InitializeControlParameters();
            }
        }
    }
}